package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    /**
     * 创建工单
     *
     * @param model
     */
    @Override
    public boolean createTask(TaskViewModel model) {
        //工单校验
        checkCreateTask(model.getInnerCode(), model.getProductType());

        if (hasTask(model.getInnerCode(), model.getProductType())){
            throw new LogicException("该机器有未完成的同类型工单");
        }
        TaskEntity taskEntity = new TaskEntity();

        //生成工单编号
        generateTaskCode();
        //设置工单编号
        taskEntity.setTaskCode(generateTaskCode());
        //执行人id
        taskEntity.setUserId(model.getUserId());
        //创建类型
        taskEntity.setCreateType(model.getCreateType());
        //设备编号
        taskEntity.setInnerCode(model.getInnerCode());
        //指派人id
        taskEntity.setAssignorId(model.getAssignorId());
        //工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);
        //工单类型
        taskEntity.setProductTypeId(model.getProductType());

        //执行人名称
        UserVO user = userService.getUser(model.getUserId());
        if (user == null){
            throw new LogicException("执行人不存在");
        }
        taskEntity.setUserName(user.getUserName());

        //根据设备编号查询设备地址和区域id
        VmVO vmInfo = vmService.getVMInfo(model.getInnerCode());

        taskEntity.setAddr(vmInfo.getNodeAddr());
        taskEntity.setRegionId(vmInfo.getRegionId());

        save(taskEntity);

        //如果是补货工单，向工单明细表插入记录
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            List<TaskDetailsViewModel> details = model.getDetails();
            for (TaskDetailsViewModel detail : details) {
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(detail, detailsEntity);
                taskDetailsService.save(detailsEntity);
            }
        }
        updateTaskZSet(taskEntity, 1);

        return true;
    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(long id) {
        TaskEntity taskEntity = this.getById(id);
        if (taskEntity.getTaskStatus() == VMSystem.TASK_STATUS_FINISH || taskEntity.getTaskStatus() ==VMSystem.TASK_STATUS_CANCEL){
            throw new LogicException("工单已经结束");
        }
        //修改工单状态
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        this.updateById(taskEntity);
        //如果是投放工单或撤机工单
        if (taskEntity.getTaskStatus() == VMSystem.TASK_TYPE_DEPLOY || taskEntity.getTaskStatus() == VMSystem.TASK_TYPE_REVOKE){
            noticeVMServiceStatus(taskEntity);
        }
        //如果是补货工单
        if (taskEntity.getTaskStatus() == VMSystem.TASK_TYPE_SUPPLY){
            noticeVMServiceSupply(taskEntity);
        }
        return true;
    }

    /**
     * 获取同一天内工单最少的人
     *
     * @param regionId
     * @param isRepair
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        //运营人员
        String role = "1002";
        //如果是维修工单
        if (isRepair){
            //运维人员
            role = "1003";
        }

        String key = VMSystem.REGION_TASK_KEY_PREF + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) +
                "." + regionId + "." + role;
        //根据key查询工单量最少的人
        Set<Object> range = redisTemplate.opsForZSet().range(key, 0, 1);

        if (range == null || range.isEmpty()){
            throw new LogicException("该区域没有相关人员");
        }
        return (Integer)range.stream().collect(Collectors.toList()).get(0);
    }


    private void noticeVMServiceSupply(TaskEntity taskEntity) {
        QueryWrapper<TaskDetailsEntity> queryWrapper = new QueryWrapper<>();
        //根据工单id查询工单明细表
        queryWrapper.lambda().eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId());
        List<TaskDetailsEntity> details = taskDetailsService.list(queryWrapper);
        //构建协议内容
        SupplyContract supplyContract = new SupplyContract();
        //售货机编号
        supplyContract.setInnerCode(taskEntity.getInnerCode());
        List<SupplyChannel> supplyChannels = new ArrayList<>();
        for (TaskDetailsEntity detailsEntity : details) {
            SupplyChannel supplyChannel = new SupplyChannel();
            //货道编号
            supplyChannel.setChannelId(detailsEntity.getChannelCode());
            //货道容量
            supplyChannel.setCapacity(detailsEntity.getExpectCapacity());
            supplyChannels.add(supplyChannel);
        }
        supplyContract.setSupplyData(supplyChannels);
        try {
            mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 1,supplyContract);
        } catch (JsonProcessingException e) {
            log.error("发送工单协议出错");
        }
    }

    private void noticeVMServiceStatus(TaskEntity taskEntity) {
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        //售货机编号
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());
        //工单类型
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 1,taskCompleteContract);
        } catch (JsonProcessingException e) {
            log.error("发送工单协议出错");
        }
    }

    /**
     * 查询同一台设备是否存在未完成的工单
     * @param innerCode
     * @param productType
     * @return
     */
    private boolean hasTask(String innerCode, int productType) {
        //构造查询
        QueryWrapper<TaskEntity> queryWrapper = new QueryWrapper<>();
        //根据条件查询
        queryWrapper.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode, innerCode)
                .eq(TaskEntity::getProductTypeId, productType)
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS);

        return this.count(queryWrapper) > 0;
    }

    /**
     * 创建工单校验
     * @param innerCode
     * @param productType
     */
    private void checkCreateTask(String innerCode, int productType) {
        //根据设备编号查询设备
        VmVO vmInfo = vmService.getVMInfo(innerCode);

        if (vmInfo == null){
            throw new LogicException("设备不存在");
        }

        //如果是投放工单，状态为运营
        if (vmInfo.getStatus() == VMSystem.VM_STATUS_RUNNING && productType == VMSystem.TASK_TYPE_DEPLOY){
            throw new LogicException("设备已在运营");
        }

        //如果是撤机工单，状态不是运营
        if (vmInfo.getStatus() != VMSystem.VM_STATUS_RUNNING && productType == VMSystem.VM_STATUS_REVOKE){
            throw new LogicException("设备不在运营状态");
        }

        //如果是补货工单，状态不是运营
        if (vmInfo.getStatus() != VMSystem.VM_STATUS_RUNNING && productType == VMSystem.TASK_TYPE_SUPPLY){
            throw new LogicException("设备不在运营状态");
        }
    }

    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd.task.code" + date;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null){
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        return date + Strings.padStart(redisTemplate.opsForValue().increment(obj, 1).toString(), 4, '0');
    }

    /**
     * 更新工单量列表
     * @param taskEntity
     * @param score
     */
    public void updateTaskZSet(TaskEntity taskEntity, int score){
        //运营人员
        String role = "1002";
        //如果是维修工单
        if (taskEntity.getProductTypeId().intValue() == 1){
            //运维人员
            role = "1003";
        }

        String key = VMSystem.REGION_TASK_KEY_PREF + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) +
                "." + taskEntity.getRegionId() + "." + role;

        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score);
    }

}
